<?php
namespace Home\Controller;
use Think\Controller;
use Think;
class ApiController extends Controller {
    
    
   /**
    * 访问该文件的接口，都需要获取code值，作为参数传入
    * 
    * date:2016年11月25日
    * author: EK_熊
    */
    
    public function __initialize(){
        $this->checkCode(I('code')); 
    }
    
    public function _debug($msg){
        if (is_array($msg)) $msg = json_encode($msg); 
        Think\Log::write($msg);
    }
    
    /**
     * 检查code有效性
     * @param unknown $code
     * date:2016年11月25日
     * author: EK_熊
     */
    private  function checkCode($code){
        
        $map['status']=1;
        $map['code'] = $code;
        $project = M('Project')->where($map)->find();
        if (!$project) {
            $data['info']='非法code';
            $data['status']=false;
            $this->ajaxReturn($data);
            exit();
        }
        return true;
    }
    
    
    /**
     * 登录接口，使用邮箱和密码
     * 
     * date:2016年11月25日
     * author: EK_熊
     */
    public function login_email(){
        $password = I('password'); //参数password
        $illegal = I('illegal');
        $map['email']=I('account');   //参数account
        $field = I('field');
        $baseField = ['ep_id'=>'id','ep_name'=>'name','email','nickname','avatar','status','password'];
        if (!empty($field)){
            $field = explode(',',$field);
            $field = array_merge($baseField,$field);
        }else{
            $field = $baseField;
        }
//         $this->debug($field);
        $userInfo = M('employee_user')->alias('user')
                ->join('__EMPLOYEE_DEPARTMENT__ dep ON dep.dep_id = user.department_id')
                ->join('__EMPLOYEE_POSITION_LVL__ plv ON plv.plv_id = user.position_lvl_id')->where($map)->field($field)->find(); 
        $data['errcode'] = 0;
        
        //获取管理员信息
        $maintain = D('Options')->getOption('maintain');
        do{
            $data['status']=false;
            if (!$userInfo){
                $data['info'] = "该账户未注册!请联系{$maintain['operation_1']}";
                $data['errcode']=1001;
                break;
            }
            
            if ($userInfo['status'] == 0) {
                $data['info'] = "该账户已被禁用(离职)，不允许登录!请联系{$maintain['operation_1']}";
                $data['errcode']=1003;
                break;                
            }
            
            $true_pwd = $illegal == true ? $password : sp_password($password);
            
            if ($true_pwd !== $userInfo['password']) {
                $data['info'] = "密码错误,如果需要找回密码,请联系{$maintain['operation_1']}";
                $data['errcode']=1002;
                break;
            }
            
            unset($userInfo['status']);
            unset($userInfo['password']);
            $data = $userInfo;
            
            $data['status'] = true;
            $data['errcode'] = 0;
        }while(false);
        $this->ajaxReturn($data);
        
    }
    
    
    /**
     * 重置密码
     * pwd_old:旧密码
     * pwd_new:新密码
     * uid:用户id
     * 
     * date:2016年12月1日
     * author: EK_熊
     */
    public function reset_password(){
        $pwd_old = I('pwd_old');
        $pwd_new = I('pwd_new');
        $uid = I('uid');
        $data['status'] =false;

      
        
        $userModel = M('employee_user');
        
        if (empty($pwd_old) || empty($pwd_new)) {
            $data['errcode'] = 3001;
            $data['info'] = '请传入正确的参数';
            $this->ajaxReturn($data);
        }
        $map['ep_id'] = $uid;
        $userInfo = $userModel->where($map)->find();
        if (!$userInfo) {
            $data['errcode'] = 3002;
            $data['info'] = '获取不到合法用户';
            $this->ajaxReturn($data);
        }
        
        if ($userInfo['password'] !== sp_password($pwd_old)) {
            $data['errcode'] = 3003;
            $data['info'] = '请输入正确的原始密码！';
            $this->ajaxReturn($data);
        }
        
        $save['password'] = sp_password($pwd_new);
        $save['updated_time'] = CURRENT_TIME;
        $ret = $userModel->where($map)->save($save);
        if (!$ret) {
            $data['errcode'] = 3004;
            $data['info'] = '网络异常，数据修改错误！';
            $this->ajaxReturn($data);
        }
        $data['errcode'] = 0;
        $data['status'] =true;
        $data['info'] = '密码修改完成！';
        $this->ajaxReturn($data);
    }
    
    /**
     * 根据用户(uid/name/sn),批量获取用户信息，josn格式
     * 接收方式，post
     * 参数格式 'uid'=>implode(',',['1','2','3'])，uid的值要使用字符串格式传输
     * date:2016年11月29日
     * author: EK_熊
     */
    public function get_user_batch(){
        $data['errcode']=2001;
        $data['info']='非法链接';
        
        $key = I('key');
        $val = I('val');
        $field = I('field');
        if (!$key && !$val &&!$field) $this->ajaxReturn(['errcode'=>'2003','info'=>'参数错误，请使用字符串格式传递！']);
        
        $map[$key] = ['in',$val];
//         $keyfield = $key;
//         $map['status'] = 1;
        $field = empty($field) ? 'ep_id,plv_title,dep_name,email,ep_name,nickname,avatar' : $field; 
        
        $userInfo = M('employee_user')->alias('user')
                ->join('LEFT JOIN __EMPLOYEE_DEPARTMENT__ dep ON dep.dep_id = user.department_id')
                ->join('LEFT JOIN __EMPLOYEE_POSITION_LVL__ plv ON plv.plv_id = user.position_lvl_id')
                ->where($map)
                ->getField($field,true);
//         $this->debug(M('employee_user')->_sql());
        if (!$userInfo)$this->ajaxReturn(['errcode'=>2002,'info'=>'暂无数据，请检查uid是否正确']);
        $this->ajaxReturn(['errcode'=>0,'userInfo'=>$userInfo]);
    }
    
    public function debug($msg){
        if (is_array($msg)) {
            $msg = json_encode($msg);
        }
        \Think\Log::write($msg,'info');
    }
    
    
    /**
     * 根据用户字段，获取单个用户数据
     * 参数： 'field'=>'ep_name'，//可选值：ep_name,email
     *      'value'=>'用户1，用户2'，
     * date:2017年2月9日
     * author: EK_熊
     */
    public function get_user_by_field(){
        $where = I('where');//字段名称
        $field = I('field');//数据集合，使用字符串格式
        if (!$field && !$where) $this->ajaxReturn(['errcode'=>'5001','info'=>'请使用字符串格式传递正确的参数']);
        $where = json_decode(urldecode($where),true);
//         $this->debug($where);
        $ret = M('employee_user')->alias('user')
                ->join('__EMPLOYEE_DEPARTMENT__ dep ON dep.dep_id = user.department_id')
                ->join('__EMPLOYEE_POSITION_LVL__ plv ON plv.plv_id = user.position_lvl_id')
                ->where($where)->field($field)->find();
        
        if (!$ret)$this->ajaxReturn(['errcode'=>2002,'info'=>'暂无数据']);
        $this->ajaxReturn(['errcode'=>0,'ret'=>$ret]);
    }
    
    
    /**
     * 修改个人用户信息
     * uid,
     * nickname:昵称
     * avatar:头像，格式 二进制数据流，base64格式
     * 
     * date:2017年1月12日
     * author: EK_熊
     */
    public function update_user(){
        $data['info'] = '未操作';
        $data['errcode'] = 4001;
        $uid = I('uid');
        $userjson = I('userdata'); 
        $field = I('field');
        if (empty($uid)) {
            $this->ajaxReturn(['info'=>'uid参数错误！','errcode'=>4002]);
        }
        $userModel = M('EmployeeUser');
        $userdata = json_decode(urldecode($userjson),true);
        if (isset($userdata['avatar'])){
            $avatar = base64ToImg($userdata['avatar'],'avatar');
            $userdata['avatar'] = "http://".$_SERVER['SERVER_NAME'].__ROOT__.'/'.$avatar;
        }
        
        if (!$userdata) $this->ajaxReturn(['info'=>'没有需要更新的字段数据！','errcode'=>4003]);
            
        $updateUser = $userModel->where(['ep_id'=>$uid])->save($userdata);
        $userInfo = $userModel->where(['ep_id'=>$uid])->field('ep_id as id,ep_name as name,nickname,avatar,email,'.$field)->find();
        
        $data = ['errcode'=>0,'info'=>'更新完成','userInfo'=>$userInfo];
        
    
    
        $this->ajaxReturn($data);
    }
    
    
    /**
     * 获取部门,返回树状结构的select结构语句
     *  $depId ： 选中状态的部门id
     * date:2016年12月1日
     * author: EK_熊
     */
    function get_department_select(){
        $selectId = I('selectid');
        $result = M('EmployeeDepartment')->select();
        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
            $r['parentid']=$r['dep_cid'];
            $r['id']=$r['dep_id'];
            $r['selected'] = '';
            if ($selectId &&$selectId==$r['dep_id']) $r['selected'] = "selected";
            $array[] = $r;
        }
        $tree->init($array);
        $str="<option value='\$id' \$selected>\$spacer\$dep_name</option>";
        $taxonomys = $tree->get_tree(0, $str);
//         $this->debug($taxonomys);
        if (!$taxonomys){
            $this->ajaxReturn(['errcode'=>1,'info'=>'数据获取失败']);
        }
        $this->ajaxReturn(['errcode'=>0,'data'=>$taxonomys,'info'=>'数据获取成功']);
    }
    
    /**
     * 获取全部部门信息
     * 
     * date:2017年3月27日
     * author: EK_熊
     */
    function get_department(){
        $result = M('EmployeeDepartment')->field('dep_id,dep_name,dep_cid')->select();
        if (!$result){
            $this->ajax_err(1, '数据异常，获取不数据!');
        }
        $this->ajax_succ(['data'=>$result]);
    }
    
    /**
     * 获取部门全部子节点id
     * 
     * date:2017年12月19日
     * author: EK_熊
     */
    function get_department_child_id(){
        $pid = I('pid');
        $result = get_child_department_id($pid);
        if (!$result){
            $this->ajax_err(1, '数据异常，获取不数据!');
        }
        $this->ajax_succ(['data'=>$result]);
    }
    
    
    /**
     * 获取直属领导的信息
     * 
     * date:2017年3月7日
     * author: EK_熊
     */
    function get_leader_info(){
        $key = I('key');
        $val = I('val');
        $feild = I('field');
        $userModel = M('EmployeeUser'); 
        $join = '__EMPLOYEE_DEPARTMENT__ ON __EMPLOYEE_DEPARTMENT__.dep_id = __EMPLOYEE_USER__.department_id';
        $leaderID = $userModel->where([$key=>$val])->getField('leader_id');
        $leader = $userModel->where(['ep_id'=>$leaderID])->join($join)->field($feild)->find();
//         $this->debug($userModel->_sql());
        if (!$leader){
            $this->ajaxReturn(['errcode'=>1,'info'=>'数据获取失败！']);
        }
        $this->ajaxReturn(['errcode'=>0,'data'=>$leader,'info'=>'数据获取成功']);
    }
    
    /**
     * 获取上一级的审核人信息
     * 
     * date:2017年6月20日
     * author: EK_熊
     */
    function get_approver_info(){
        $sn = I('sn');
        $feild = I('field');
        $userModel = M('EmployeeUser');
        $join = '__EMPLOYEE_DEPARTMENT__ ON __EMPLOYEE_DEPARTMENT__.dep_id = __EMPLOYEE_USER__.department_id';
        $where['sn'] = $sn;
        $where['status'] = 1;
        $leaderID = $userModel->where($where)->getField('approver_id');
        $leader = $userModel->where(['ep_id'=>$leaderID,'status'=>1])->join($join)->field($feild)->find();
//         $this->debug($userModel->_sql());
        if (!$leader){
            $this->ajaxReturn(['errcode'=>1,'info'=>'数据获取失败！']);
        }
        $this->ajaxReturn(['errcode'=>0,'data'=>$leader,'info'=>'数据获取成功']);        
    }
    
    /**
     * 
     * 获取【限定数量】的员工的基础信息，只能获取到一些基础的信息
     * 比如，工号，姓名，部门id
     * date:2017年3月16日
     * author: EK_熊
     */
    public function get_all_user_baseinfo(){
      $page = I('page');     
      $limit = I('limit');     
      $field = I('field');
      $where = json_decode(urldecode(I('where')),true);
      if ($where) $map = $where;
//       $map['status'] = isset($where['status']) ? $where['status'] : 1;
      $join = '__EMPLOYEE_DEPARTMENT__ ON __EMPLOYEE_DEPARTMENT__.dep_id = __EMPLOYEE_USER__.department_id';
      if ($limit == 0) {
          $ret = M('EmployeeUser')->where($map)->join($join)->getField($field,true);
      }else{
          $ret = M('EmployeeUser')->where($map)->join($join)->page($page,$limit)->getField($field,true);
      }
    //  $this->debug(M('EmployeeUser')->_sql());
      if (!$ret) $this->ajax_err(2, '数据获取失败！');
      $this->ajax_succ(['data'=>$ret]);
    }
   
    
    /**
     * 获取单个用户的哺乳期信息
     * 
     * date:2017年4月13日
     * author: EK_熊
     */
    public function get_suckling_info(){
        $sn = I('sn');
        $where['sn'] = $sn;
        $curday = date('Y-m-d');
        $where['date_start'] = ['elt',"$curday 00:00:00"];
        $where['_string'] = "`date_end` ='$curday' or `date_end` > '$curday 23:59:59'";
        $data = M('EmployeeSuckling')->where($where)->field('date_start,date_end,work_hour')->find();
        if (!$data) $this->ajax_err(2, '数据获取失败！');
        $this->ajax_succ(['data'=>$data]);
    }
    
    /**
     * 获取高管行程名单，即privilege=4
     * 
     * date:2017年7月21日
     * author: EK_熊
     */
    public function get_schedule_list(){
        
        $where['privilege'] = ['like',"%4%"];
        $where['status'] = 1;
//         $data = M('EmployeeUser')->where($where)->getField('sn,privilege,ep_name,ep_id');
        $join = [
            '__EMPLOYEE_DEPARTMENT__ ON __EMPLOYEE_DEPARTMENT__.dep_id = __EMPLOYEE_USER__.department_id',
            '__EMPLOYEE_POSITION__ ON __EMPLOYEE_POSITION__.pos_id = __EMPLOYEE_USER__.position_id',
        ];
        $data = M('EmployeeUser')->where($where)->field('sn,privilege,ep_name,ep_id,dep_name,pos_title')->join($join)->select();
        //要排除，40,44等其他情况
        foreach ($data as $k=>$v){
            if (strstr($v['privilege'],'4') !== '4'){
                unset($data[$k]);
            }
        }
//         $this->debug(M('EmployeeUser')->_sql());
        if (!$data) $this->ajax_err(2, '数据获取失败！');
        $this->ajax_succ(['data'=>$data]);        
    }
    
    
    /**
     * 批量获取领导信息
     * 
     * date:2017年5月27日
     * author: EK_熊
     */
    public function get_leader_info_all(){
        $where = I('where');
        $field = I('field');
        $where = json_decode(urldecode($where),true);
        
        $userModel = M('EmployeeUser');
        $leader_id_box = $userModel->group('leader_id')->where($where)->getField('leader_id',true);
        
        $data = $userModel->where(['ep_id'=>['in',$leader_id_box],'status'=>1])->field($field)->select();
        if (!$data) $this->ajax_err(2, '数据获取失败！');
        $this->ajax_succ(['data'=>$data]);
    }
    
    /**
     * 获取全部审核人工号
     * 
     * date:2017年7月26日
     * author: EK_熊
     */
    public function get_approver_sn(){
        $data =D('EmployeeUser')->get_approver_list();
        
        if (!$data) $this->ajax_err(2, '数据获取失败！');
        $this->ajax_succ(['data'=>$data]);
    }
    
    
    public function ajax_err($code,$msg){
        $data['errcode'] = $code;
        $data['info'] = $msg;
        $this->ajaxReturn($data);
    }
    
    public function ajax_succ($data=[],$msg='操作完成'){
        $data['errcode'] = 0;
        $data['info'] = $msg;
        $this->ajaxReturn($data);
    }

    
}